import logging
import re

import json
from datetime import datetime, timedelta
from common import constants
import credit_voice_service.dialogue.cache.constants as constant
from credit_voice_service.dialogue.factory.base_info.strategy.base_info_factory import BaseInfoData
from dialogue.util.date_transmission import send_data_by_es


class dataHandlingUtil(object):
    def __init__(self):
        pass

    def data_handling_user_info(self, user_info, session_id):
        baseInfoData = BaseInfoData()
        return baseInfoData.get_base_info_data(session_id, user_info)

    def data_handling_msg_data(self, conversation_history, result, type, query_time):
        if not conversation_history:
            conversation_history = []
        conversation_dict = {}
        if type == constants.ROLE_USER:
            conversation_dict["role"] = constants.ROLE_USER
            conversation_dict["content"] = result
            conversation_dict["query_time"] = query_time
            try:
                if conversation_history and len(conversation_history) != 0 and conversation_history[
                    -1] and constants.ROLE_USER == conversation_history[-1].get('role'):
                    query_time_history = conversation_history[-1].get('query_time')
                    query_time_history_time = datetime.strptime(query_time_history, '%Y-%m-%d %H:%M:%S')
                    query_time_time = datetime.strptime(query_time, '%Y-%m-%d %H:%M:%S')
                    delta = timedelta(milliseconds=int(len(result) / 5 * 200))
                    query_time_time -= delta
                    td = query_time_time - query_time_history_time
                    total_seconds = int(td.total_seconds())
                    if total_seconds >= 5:
                        conversation_dict["interval"] = total_seconds
            except Exception:
                logging.error('获取用户对话记录计算时间报错')
        else:
            conversation_dict["role"] = constants.ROLE_ASSISTANT
            conversation_dict["content"] = result['reply_text']
            conversation_dict["query_time"] = query_time
            conversation_dict["user_question"] = result['user_question']
            conversation_dict["sales_skill_name"] = result['sales_skill_name']
        conversation_history.append(conversation_dict)
        return conversation_history

    def calculate_user_question_times(self, dialogue_session, base_info):

        try:
            # 拒绝次数计算
            # 计算出一次拒绝，三次拒绝
            refuse_times = 0
            for dialogue_info in dialogue_session['dialogueHistory']['dialogueItemList'][::-1]:
                user_question = dialogue_info['llmResult']['intention'][0]['user_question']

                # 出现拒绝类标签计数，出现非拒绝类标签跳出循环
                if user_question in ['不需要', '在忙', '会考虑']:
                    refuse_times += 1
                else:
                    break

            base_info['refuse'] = refuse_times

        except Exception as err:
            pass

        '''try:
            # 连续相同用户问题次数
            user_question_list = list()
            for dialogue_info in dialogue_session['dialogueHistory']['dialogueItemList'][::-1]:
                user_question = dialogue_info['llmResult']['intention'][0]['user_question']
                user_question_list.append(user_question)

            # 最后三轮
            if len(user_question_list) > 3:
                pass
            user_question_list[:3]

        except Exception as err:
            pass'''

        return base_info

    def update_session_history(self, dialogue_session, workspace_id, user_content, seat_content, query_time,
                               id_result_json):
        if id_result_json is None:
            id_result_json = {}
        dialogue_session['dialogueHistory']['dialogueItemList'].append({
            "workspaceId": workspace_id,
            'query': user_content,
            'reply': seat_content,
            "replyTime": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "queryTime": query_time,
            'llmResult': id_result_json,
        })
        return dialogue_session

    def data_handling_result(self, llm_data, base_info, start=False):
        result = self.get_result_data(llm_data, base_info, start)
        # ES 存储json data
        id_result_json = self.get_llm_result_json(llm_data)

        return result, id_result_json

    def get_result_data(self, llm_data, base_info, start):
        result = ''
        label = []
        if llm_data.get('user_question', '') and '无' != llm_data.get('user_question', ''):
            user_question = llm_data.get('user_question', '')
            user_question = user_question.replace(" ", "")
            result = '[用户问题:{}]'.format(user_question)
        if llm_data.get('sales_skill_name', '') and '无' != llm_data.get('sales_skill_name', ''):
            sales_skill_name = llm_data.get('sales_skill_name', '')
            sales_skill_name = sales_skill_name.replace(" ", "")
            result = result + '[销售技巧:{}]'.format(sales_skill_name)
        if llm_data.get('label', ''):
            label = llm_data.get('label').split(',')
            for item in label:
                if constant.ACTION_SEND_SMS_COM in item:
                    result = result + '[{}]'.format(constant.ACTION_SEND_SMS_COM)
                elif constant.ACTION_ADD_BLACK in item:
                    result = result + '[{}]'.format(constant.ACTION_ADD_BLACK)
                elif constant.ACTION_SEND_SMS in item:
                    result = result + '[{}]'.format(constant.ACTION_SEND_SMS)
                elif constant.ACTION_ADD_WECHAT in item:
                    result = result + '[{}]'.format(constant.ACTION_ADD_WECHAT)
                elif constant.ACTION_SEND_CERTIFICATE_COM == item:
                    result = result + '[{}]'.format(constant.ACTION_SEND_CERTIFICATE_COM)
                elif constant.ACTION_SEND_CERTIFICATE_COM_M in item:
                    certificate = base_info.get('券信息', '')
                    if certificate:
                        result = result + '[{}{}]'.format(constant.ACTION_SEND_CERTIFICATE_COM_M, certificate)
        voice_record = llm_data.get('voice_record', '')
        if voice_record:
            resultList = voice_record.split(',')
            for record in resultList:
                result = result + '@#{}||0#@'.format(record)
            result = result + llm_data.get('reply_text', '')
        else:
            result = result + '@#{}||{}#@'.format(llm_data.get('reply_text', ''), llm_data.get('reply_text', ''))
            result = result + llm_data.get('reply_text', '')
        if label:
            for item in label:
                if constant.ACTION_END in item:
                    result = result + constant.LABEL_END
        if llm_data.get("is_transfer"):
            result = result + constant.LABEL_TRANSFER.replace("NUMBER", llm_data.get("transfer_success"))
        if start:
            result = result + constant.LABEL_NOT_BREAK + constant.LABEL_QUIET
        return result

    def get_llm_result_json(self, llm_data):
        id_result_json = {
            'intention': [{
                'user_question': llm_data.get('user_question', ''),
                'user_question_prompt': llm_data.get('user_question_prompt', ''),
                'sales_skill_name': llm_data.get('sales_skill_name', ''),
                'sales_skill_name_prompt': llm_data.get('sales_skill_name_prompt', ''),
                'user_situation': llm_data.get('user_situation', ''),
                'user_situation_prompt': llm_data.get('user_situation_prompt', ''),
                'solution': llm_data.get('solution', ''),
                'skill_knowledge': llm_data.get('skill_knowledge', ''),
                'solution_knowledge': llm_data.get('solution_knowledge', ''),
                'conversation_prompt': llm_data.get('conversation_prompt', ''),
            }, ],
            'voice_record': llm_data.get('voice_record', ''),
            'reply_text': llm_data.get('reply_text', ''),
        }
        return id_result_json

    def data_dialogue_session_start(self, session_id, workspace_id, dialogue_id, result, dialogue_conf):
        result["dialogue_conf"] = dialogue_conf
        companyId = None
        webhook = ''
        model_name = ''
        if "dialogue_config" in dialogue_conf and dialogue_conf["dialogue_config"]:
            dialogue_config = json.loads(dialogue_conf["dialogue_config"])
            companyId = dialogue_config["companyId"]
            webhook = dialogue_config.get('webhook', '')
            model_name = dialogue_config.get('model_name', '')
        bot_name = dialogue_conf.get('dialgoue_name', '')
        dialogueSession = {}
        faqId = dialogue_conf.get('faq_id', '')
        llm_service_ip = dialogue_conf.get("llm_service_ip", '')
        dialogueSession["sessionId"] = session_id
        dialogueSession["workspaceId"] = workspace_id
        dialogueSession["accessDialogueId"] = dialogue_id
        dialogueSession["faqWorkspaceId"] = faqId
        dialogueSession["companyId"] = companyId
        dialogueSession["webhook"] = webhook
        dialogueSession["bot_name"] = bot_name
        dialogueSession["model_name"] = model_name
        dialogueSession["llm_service_ip"] = llm_service_ip
        dialogueSession["transfer_content"] = dialogue_conf["transfer_content"]
        dialogueItemList = []
        dialogueHistory = {}
        dialogueHistory["dialogueItemList"] = dialogueItemList
        dialogueSession["dialogueHistory"] = dialogueHistory
        return dialogueSession, result

    def create_dialogue_info(self, msg_content, workspace_id, speaker_type, session_id, dialogue_round, score="",
                             request_time=None, id_result_json=None, conversation_history=None):
        contentLabel = []
        botWordsText = ''
        recordNumber = ''
        if id_result_json is None:
            id_result_json = {}
        else:
            recordNumber = id_result_json.get('voice_record')
            botWordsText = id_result_json.get('reply_text')
        id_result_json['conversation_history'] = conversation_history
        if msg_content is not None and msg_content != "":
            pattern = r'\[(.*?)\]'  # 匹配[]中的内容
            contentLabel = re.findall(pattern, msg_content)
        if request_time is None:
            request_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        dialogue_info = {
            "msgContent": msg_content,
            "workspaceId": workspace_id,
            "speakerType": speaker_type,
            "sessionId": session_id,
            "userId": session_id,
            "msgTime": request_time,
            "dialogueRound": dialogue_round,
            "score": score,
            "contentLabel": contentLabel,
            "botWordsText": botWordsText,
            "recordNumber": recordNumber,
            "llmResult": id_result_json
        }

        send_data_by_es(session_id, dialogue_info)


dataHandling = dataHandlingUtil()

if __name__ == '__main__':
    dataHandling = dataHandlingUtil()
    print(dataHandling.data_handling_user_info('', ''))
    pass
